package com.itheima.controller;

import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/validatecode")
public class ValidateCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 体检预约发送验证码
     * @param telephone
     * @return
     */
    @PostMapping("/send4Order")
    public Result send4Order(String telephone){
        Integer validateCode = getValidateCodeWithExpireTime(4,
                RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone,
                5, TimeUnit.MINUTES);

        return new Result(true, String.valueOf(validateCode));
    }

    /**
     * 用户登录发送验证码
     * @param telephone
     * @return
     */
    @GetMapping("/send4Login")
    public Result send4Login(String telephone){
        Integer validateCode = getValidateCodeWithExpireTime(6,
                RedisMessageConstant.SENDTYPE_LOGIN + "_" + telephone,
                5, TimeUnit.MINUTES);

        return new Result(true, String.valueOf(validateCode));
    }

    public Integer getValidateCodeWithExpireTime(Integer codeLength, String key,
                                                 Integer expireTime, TimeUnit timeUnit){
        // 随机生成长度为codeLength的数字验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(codeLength);
        redisTemplate.opsForValue().set(key, validateCode, expireTime, timeUnit);

        return validateCode;
    }
}
